﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interfleet.SE.UICompiler.Core;
using Interfleet.SE.UICompiler.UI.Views;
using System.Threading;

namespace Interfleet.SE.UICompiler.UI
{
    /// <summary>
    /// Controller for Views
    /// </summary>
    public class UIController
    {
        private Thread WorkerThread
        {
            get;
            set;
        }

        private IUCompilerView View
        {
            get;
            set;
        }

        public void Start(IUCompilerView view)
        {
            var agentFactory = CompileAgentFactory.CreateAgentFactory(CompileType.ClosureCompilerREST);
            view.SetCompileOptionList(agentFactory.GetCompileOptions());
            view.SetCompileType(CompileType.ClosureCompilerREST);
            view.Compile += new Handlers.CompileHandler(view_Compile);
            view.CompileTypeChanged += new Handlers.CompileTypeChangedHandler(view_CompileTypeChanged);
            View = view;
        }

        void view_CompileTypeChanged(IUCompilerView view, CompileTypeChangedEventArgs e)
        {
            view.SetCompileType(e.CompileType);
            var agentFactory = CompileAgentFactory.CreateAgentFactory(e.CompileType);
            view.SetCompileOptionList(agentFactory.GetCompileOptions());
        }

        

        private void view_Compile(IUCompilerView view, CompileEventArgs e)
        {
            var agentFactory = CompileAgentFactory.CreateAgentFactory(e.CompileType);
            var closureCompilerAgent = agentFactory.CreateCompilerAgent(e.Arguments);
            closureCompilerAgent.CompilationDone += new CompilerAgent.CompilationDoneHandler(closureCompilerAgent_CompilationDone);
            WorkerThread = new Thread(new ThreadStart(closureCompilerAgent.CompileAsync));
            WorkerThread.Start();
            
        }

        private void closureCompilerAgent_CompilationDone(CompileResult result)
        {
            View.ShowResult(result);
        }

        private static UIController _instance;

        public static UIController Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new UIController();
                }
                return _instance;
            }
        }


    }
}
